package com.wyix;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class FileClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入服务端IP（默认localhost）: ");
        String host = scanner.nextLine().trim();
        if (host.isEmpty()) host = "localhost";

        try (Socket socket = new Socket(host, 9999);
             DataOutputStream out = new DataOutputStream(socket.getOutputStream());
             DataInputStream in = new DataInputStream(socket.getInputStream());
             BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.println("选择操作（1-上传 / 2-下载）: ");
            int choice = Integer.parseInt(reader.readLine());

            if (choice == 1) {
                // 执行文件上传
                System.out.print("输入本地文件路径（如C:/test.txt）: ");
                String localPath = reader.readLine();
                File file = new File(localPath);

                if (!file.exists()) {
                    System.out.println("文件不存在！");
                    return;
                }

                out.writeUTF("UPLOAD");  // 发送操作类型
                out.writeUTF(file.getName());  // 发送文件名
                out.writeLong(file.length());  // 发送文件大小
                out.flush();

                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    out.flush(); // 确保最后一批数据发送
                }

                // 接收服务端响应
                try {
                    System.out.println("服务端响应：" + in.readUTF());
                } catch (EOFException e) {
                    System.err.println("错误：服务端提前关闭连接，未发送响应");
                } catch (UTFDataFormatException e) {
                    System.err.println("错误：服务端返回数据非UTF-8格式");
                }
            } else if (choice == 2) {
                // 执行文件下载
                System.out.print("输入要下载的文件名（如test.txt）: ");
                String fileName = reader.readLine();

                out.writeUTF("DOWNLOAD");
                out.writeUTF(fileName);
                out.flush();

                String response = in.readUTF();
                if ("FILE_EXISTS".equals(response)) {
                    long fileSize = in.readLong();
                    System.out.print("输入保存路径（如D:/download/）: ");
                    String savePath = reader.readLine();

                    // 处理保存路径，确保以文件分隔符结尾
                    if (!savePath.endsWith(File.separator)) {
                        savePath += File.separator;
                    }

                    File saveDir = new File(savePath);
                    if (!saveDir.exists()) {
                        if (!saveDir.mkdirs()) {
                            System.out.println("创建保存目录失败！");
                            return;
                        }
                    }

                    File saveFile = new File(savePath + fileName);
                    try (FileOutputStream fos = new FileOutputStream(saveFile)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        long received = 0;

                        while (received < fileSize && (len = in.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                            received += len;
                        }
                        System.out.println("文件下载完成，保存至：" + saveFile.getAbsolutePath());
                    }
                } else {
                    System.out.println(response);
                }
            } else {
                System.out.println("无效操作选择");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    }
}